import { NextFunction, Request, Response } from 'express'
import { Unauthorized, Forbidden } from 'http-errors'
import { failure } from '@/utils/response'
import User from '@/database/models/user'

const roleAuth = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
  try {
    const allowedRoles = [2, 3, 4, 100]
    const user = await User.findByPk(req.userId)
    if (!user) {
      throw new Unauthorized('用户不存在。')
    }
    if (!allowedRoles.includes(user.roleId)) {
      throw new Forbidden('您没有权限浏览，请先购买管理员权限后再访问。')
    }
    next()
  } catch (error) {
    failure(res, error as Error)
  }
}

export default roleAuth
